#include <json.hpp>
#include <iostream>
#include <string>

#include <stdio.h>
#include "read_jansson.h"

void show_help() {
  std::cout << "#> read_jansson <pid> <addr> [compact]" << std::endl;
  std::cout << "\tpid\t\tDestination process ID: 2516" << std::endl;
  std::cout << "\taddr\t\tDestination memory address: 0x02d149b8" << std::endl;
  std::cout << "\tcompact\t\tBeautify JSON: True/false" << std::endl;
}

void* hex2addr(const char *hexstr) {
  uint64_t d = 0;
  sscanf(hexstr, "%x", &d);
  return (void*)d;
}

int main(int argc, char *argv[]) {
  pid_t pid = 0;
  void *addr = (void*)0;
  bool compact = true;
  if (argc < 3) {
    show_help();  
    return 0;
  } else if (argc > 3) {
    compact = (0 != strcmp(argv[3], "false"));
  }
  pid = (pid_t)atoll(argv[1]);
  addr = hex2addr(argv[2]);

  if (pid == 0 || !addr) {
    std::cout << "Error " << (pid == 0 ? "pid" : "addr") << std::endl;
    return 0;
  }

  std::cout << "Read pid " << pid
      << " addr " << argv[2]
      << " with compact " << (compact ? "true" : "false")
      << std::endl;
  std::cout << "----------" << std::endl;
  json::Json rst(read_jansson(pid, addr));
  auto str = rst->dumps(compact ? JSON_COMPACT : 0);
  if (str) std::cout << str << std::endl;
  else std::cout << "Read error." << std::endl;
  json::dumpsFree(str);
  rst->decref();

  return 0;
}